<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\SciencesModel;

class SciencesDao extends BaseDao
{

    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = SciencesModel::query();

        $query->when(checkIsHasField($params,'show'),function ($query)use ($params){
            $query->where('show',$params['show']);
        });

        $query->when(checkIsHasField($params,'sciences_id'),function ($query)use ($params){
            $query->where('sciences_id',$params['sciences_id']);
        });


        $query->when(checkIsHasField($params,'title_like'),function ($query)use ($params){
            $query->where('title','like','%'.$params['title_like'].'%');
        });



        return $query->orderByDesc('created_at');
    }



    public static function videos($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->paginate();
    }


    /**
     * @throws SysExceptions
     */
    public static function videosCreate($params = []){
        if (self::builder_query()->create($params) === false){
            self::error('创建失败');
        }
    }

    /**
     * @desc 修改失败
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function edit(array $params)
    {
        if(self::builder_query(['sciences_id'=>self::deleteParamId($params,'sciences_id')])->update(self::filterFields($params,new SciencesModel())) === false){
            self::error('修改失败');
        }
    }

    public static function info(array $all): array
    {
        return self::builder_query($all)->first()->toArray();
    }

    public static function delete(array $all)
    {
        if(self::builder_query(['sciences_id'=>$all['id']])->delete() === false){
            self::error('删除失败');
        }
    }
}
